import type { AcctInfo, CertInfo, ContactInfo, LicenseInfo, MerInfo, OperatorInfo, SettlementInfo } from '@/types'
import apply from '@/api/apply'

interface StepWithText {
  title: string
}

export const useApplyStore = defineStore(
  'apply',
  () => {
    const phoneNumber = ref('')
    const mer_type = ref('3')
    const steps = ref<Array<string>>([])
    const currentStep = ref(0)
    const stepsWithText = computed<Array<StepWithText>>(() => {
      return steps.value.map((step: string) => {
        let title = ''
        switch (step) {
          case "owner":
            title = "法人信息";
            if (mer_type.value === "3") {
              title = "负责人信息";
            } else if (mer_type.value === "1") {
              title = "经营者信息";
            }
            break;
          case "operator":
            title = "法人信息";
            // || mer_type.value === '6'
            if (mer_type.value === "1") {
              title = "经营者信息";
            }
            if (mer_type.value === "6") {
              title = "责任人信息";
            }
            break;
          case "small":
            title = "商户信息";
            break;
          case "acct":
            title = "结算签约";
            break;
          case "cert":
            title = "证照信息";
            break;
          case "contact":
            title = "联系人信息";
            break;
          case "settlement":
            title = "结算签约";
            break;
        }
        return { title }
      })
    })
    const applyId = ref('')

    const originImageList = ref({
      fileType5: { // 身份证正面
        name: '',
        url: '',
        status: 'ready',
        message: '上传成功',
        type: 'image',
      },
      fileType6: { // 身份证背面
        name: '',
        url: '',
        status: 'ready',
        message: '上传成功',
        type: 'image',
      },
      fileType20: { // 银行卡正面
        name: '',
        url: '',
        status: 'ready',
        message: '上传成功',
        type: 'image',
      },
      fileType54: { // 执照
        name: '',
        url: '',
        status: 'ready',
        message: '上传成功',
        type: 'image',
      },
      fileType51: { // 经营者身份证正面
        name: '',
        url: '',
        status: 'ready',
        message: '上传成功',
        type: 'image',
      },
      fileType52: { // 经营者身份证背面
        name: '',
        url: '',
        status: 'ready',
        message: '上传成功',
        type: 'image',
      },
    })

    const originCertInfo = ref<CertInfo>({
      certType: '',
      certName: '',
      certNo: '',
      certStartDate: '',
      certEndDate: '',
      certAddr: '',
      phoneNumber: '',
    })

    const originMerInfo = ref<MerInfo>({
      merName: '',
      merShortName: '',
      businessStatus: '0',
      longitude: 0,
      latitude: 0,
      businessAddr: '',
    })

    const originAcctInfo = ref<AcctInfo>({
      settleAcct: '',
      acctName: '',
      bankName: '',
      managerNo: '',
      managerName: '',
    })

    const originLicenseInfo = ref<LicenseInfo>({
      certType: '',
      certNo: '',
      merName: '',
      merShortName: '',
      certStartDate: '',
      certEndDate: '',
      respPerson: '',
      regCap: '',
      certAddrProv: '',
      certAddrCity: '',
      certAddrDist: '',
      certAddrDet: '',
      // bizAddrProv: '',
      // bizAddrCity: '',
      // bizAddrDist: '',
      latitude: 0,
      longitude: 0,
      bizAddrDet: '',
    })

    const originOperatorInfo = ref<OperatorInfo>({
      respCertType: '01',
      respCertName: '',
      respCertNo: '',
      respCertStartDate: '',
      respCertEndDate: '',
      respCertAddrDet: '',
      isSpecContact: '0',
    })

    const originContactInfo = ref<ContactInfo>({
      contactCertType: '01',
      contactCertName: '',
      contactCertNo: '',
      contactCertStartDate: '',
      contactCertEndDate: '',
      contactPhone: '',
      // contactCertAddrDet: '',
    })

    const originSettlementInfo = ref<SettlementInfo>({
      acctType: '01',
      acctNo: '',
      acctName: '',
      bankName: '',
      managerNo: '',
      managerName: '',
    })

    const imageList = ref(JSON.parse(JSON.stringify(originImageList.value)))
    const certInfo = ref(JSON.parse(JSON.stringify(originCertInfo.value)))
    const merInfo = ref(JSON.parse(JSON.stringify(originMerInfo.value)))
    const acctInfo = ref(JSON.parse(JSON.stringify(originAcctInfo.value)))
    const licenseInfo = ref(JSON.parse(JSON.stringify(originLicenseInfo.value)))
    const operatorInfo = ref(JSON.parse(JSON.stringify(originOperatorInfo.value)))
    const contactInfo = ref(JSON.parse(JSON.stringify(originContactInfo.value)))
    const settlementInfo = ref(JSON.parse(JSON.stringify(originSettlementInfo.value)))

    function resetSteps () {
      switch (mer_type.value) {
        // 小微企业
        case '3':
          steps.value = ['owner', 'small', 'acct']
          break
        // 个体工商户
        case '1':
          steps.value = ['cert', 'operator', 'contact', 'settlement']
          break
        // 企业
        case '2':
          steps.value = ['cert', 'operator', 'contact', 'settlement']
          break
        // 事业单位
        case '4':
          steps.value = ['cert', 'operator', 'contact', 'settlement']
          break
        // 政府机关
        case '5':
          steps.value = ['cert', 'operator', 'contact', 'settlement']
          break
        // 其他组织
        case '6':
          steps.value = ['cert', 'operator', 'contact', 'settlement']
          break
      }
    }

    function resetApplyInfo() {
      currentStep.value = 0
      imageList.value = JSON.parse(JSON.stringify(originImageList.value))
      certInfo.value = JSON.parse(JSON.stringify(originCertInfo.value))
      merInfo.value = JSON.parse(JSON.stringify(originMerInfo.value))
      acctInfo.value = JSON.parse(JSON.stringify(originAcctInfo.value))
      licenseInfo.value = JSON.parse(JSON.stringify(originLicenseInfo.value))
      operatorInfo.value = JSON.parse(JSON.stringify(originOperatorInfo.value))
      contactInfo.value = JSON.parse(JSON.stringify(originContactInfo.value))
      settlementInfo.value = JSON.parse(JSON.stringify(originSettlementInfo.value))
    }


    function setApplyInfo(info: any) {
      if (mer_type.value === '3') {
        // 载入数据
        // 处理imageList
        const { imageList: infoImageList } = info
        if (infoImageList) {
          // 找身份证正面
          const fileType5ImageInfo = infoImageList.find((x: any) => x.fileType === '5')
          if (fileType5ImageInfo && fileType5ImageInfo.imageId) {
            imageList.value.fileType5.name = fileType5ImageInfo.imageId
          }
          // 找身份证背面
          const fileType6ImageInfo = infoImageList.find((x: any) => x.fileType === '6')
          if (fileType6ImageInfo) {
            imageList.value.fileType6.name = fileType6ImageInfo.imageId
          }
          // 找银行卡正面
          const fileType20ImageInfo = infoImageList.find((x: any) => x.fileType === '20')
          if (fileType20ImageInfo) {
            imageList.value.fileType20.name = fileType20ImageInfo.imageId
          }
        }

        if (info.certNo) {
          // 第一页数据
          certInfo.value.certType = info.certType || ''
          certInfo.value.certName = info.certName || ''
          certInfo.value.certNo = info.certNo || ''
          certInfo.value.certStartDate = info.certStartDate || ''
          certInfo.value.certEndDate = info.certEndDate || ''
          certInfo.value.certAddr = info.certAddr || ''
          certInfo.value.phoneNumber = info.phoneNumber || phoneNumber.value || ''
        }

        if (info.merName) {
          // 第二页数据
          merInfo.value.merName = info.merName || ''
          merInfo.value.merShortName = info.merShortName || ''
          merInfo.value.businessStatus = info.businessStatus || '0'
          merInfo.value.longitude = info.longitude || 0
          merInfo.value.latitude = info.latitude || 0
          merInfo.value.businessAddr = info.businessAddr || ''
        }

        if (info.settleAcct) {
          // 第三页数据
          acctInfo.value.settleAcct = info.settleAcct || ''
          acctInfo.value.acctName = info.acctName || ''
          acctInfo.value.bankName = info.bankName || ''
          acctInfo.value.managerNo = info.managerNo || ''
          acctInfo.value.managerName = info.managerName || ''
        }
      } else {
        // 处理imageList
        const { imageList: infoImageList } = info
        if (infoImageList) {
          // 找联系人身份证正面
          const fileType5ImageInfo = infoImageList.find((x: any) => x.fileType === '5')
          if (fileType5ImageInfo && fileType5ImageInfo.imageId) {
            imageList.value.fileType5.name = fileType5ImageInfo.imageId
          }
          // 找联系人身份证背面
          const fileType6ImageInfo = infoImageList.find((x: any) => x.fileType === '6')
          if (fileType6ImageInfo) {
            imageList.value.fileType6.name = fileType6ImageInfo.imageId
          }
          // 找经营者身份证正面
          const fileType51ImageInfo = infoImageList.find((x: any) => x.fileType === '51')
          if (fileType51ImageInfo) {
            imageList.value.fileType51.name = fileType51ImageInfo.imageId
          }
          // 找经营者身份证背面
          const fileType52ImageInfo = infoImageList.find((x: any) => x.fileType === '52')
          if (fileType52ImageInfo) {
            imageList.value.fileType52.name = fileType52ImageInfo.imageId
          }
          // 找营业执照
          const fileType54ImageInfo = infoImageList.find((x: any) => x.fileType === '54')
          if (fileType54ImageInfo) {
            imageList.value.fileType54.name = fileType54ImageInfo.imageId
          }
          // 找银行卡正面
          const fileType20ImageInfo = infoImageList.find((x: any) => x.fileType === '20')
          if (fileType20ImageInfo) {
            imageList.value.fileType20.name = fileType20ImageInfo.imageId
          }
        }

        // 载入数据
        if (info.operatorInfo) {
          operatorInfo.value = info.operatorInfo
        }
        if (info.contactInfo) {
          contactInfo.value = info.contactInfo
        }
        if (info.licenseInfo) {
          licenseInfo.value = info.licenseInfo
        }
        if (info.settlementInfo) {
          settlementInfo.value = info.settlementInfo
        }
      }
    }

    async function getApplyInfo(selectedType: string) {
      let rep: any = {}
      if (selectedType === '3') {
        // 查小微商户提交信息
        const { data } = await apply.getSmallMerchantInfo()
        rep = data
      }
      else {
        const { data } = await apply.getMerchantInfo()
        rep = data
      }
      if (rep.status === 'success') {
        applyId.value = rep.data.applyId
        const { data: info } = rep
        // 根据返回status决定下一步操作
        const applyStatus = info.status
        const pages = getCurrentPages()
        const currentPage: any = pages[pages.length - 1]
        if (applyStatus === '01' || applyStatus === '05') {
          // 跳转list
          uni.showModal({
            title: '提示',
            content: `您已有在途的进件流程，是否继续填写？`,
            confirmText: '去查看',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                if (/login/.test(currentPage.route)) {
                  // 登录页
                  uni.redirectTo({
                    url: '/pages-sub/apply/list',
                  })
                } else {
                  uni.navigateTo({
                    url: '/pages-sub/apply/list',
                  })
                }
              }
            }
          })
        } else {
          mer_type.value = selectedType
          resetApplyInfo()
          resetSteps()
          setApplyInfo(info)
          if (/login/.test(currentPage.route)) {
            // 登录页
            uni.redirectTo({
              url: `/pages-sub/apply/input-${steps.value[0]}`,
            })
          } else {
            uni.navigateTo({
              url: `/pages-sub/apply/input-${steps.value[0]}`,
            })
          }
        }
      }
    }

    return {
      phoneNumber,
      mer_type,
      steps,
      currentStep,
      stepsWithText,
      applyId,
      certInfo,
      imageList,
      merInfo,
      acctInfo,
      licenseInfo,
      operatorInfo,
      contactInfo,
      settlementInfo,
      resetApplyInfo,
      resetSteps,
      setApplyInfo,
      getApplyInfo
    }
  },
)
